//
//  OldCollectionModel.m
//  Item A House
//
//  Created by dllo on 15/5/27.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "OldCollectionModel.h"
#import <UIKit/UIKit.h>
@implementation OldCollectionModel
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

+ (void)writeArray:(NSDictionary *)newDic
{
    NSString *path = [self path];
    
    NSArray *arr = [self readArray];
    NSMutableArray *arr1 = [NSMutableArray arrayWithArray:arr];
    BOOL judge = [self judgeData:arr object:[NSString stringWithFormat:@"%@", [newDic objectForKey:@"houseid"] ]];
    if (judge) {
        // 换成通知框
        NSLog(@"已收藏");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"收藏通知" message:@"已收藏" delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [alert show];
        
    } else {
        [arr1 addObject:newDic];
        NSLog(@"收藏成功");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"收藏通知" message:@"成功收藏" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil];
        [alert show];
    }
    [arr1 writeToFile:path atomically:YES];
}

+ (BOOL)judgeData:(NSArray *)arr object:(NSString *)object
{
    BOOL judge = NO;
    for (NSMutableDictionary *dic in arr) {
        judge = [[NSString stringWithFormat:@"%@", [dic objectForKey:@"houseid"]] isEqualToString:object];
        
        if (judge) {
            // 存在, 返回no
            return YES;
        }
        
    }
    return NO;
}
+ (void)fileExist
{
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *path = [self path];
    // 存在路径就一定存在文件, 至于文件里是否为空管不着
    
    BOOL judge = [manager fileExistsAtPath:path];
    if (judge) {
        // 存在, 没被意外删除
        NSLog(@"文件存在");
    } else
    {
        // 不存在时
        NSLog(@"文件不存在");
        NSMutableArray *arr1 = [NSMutableArray array];
        NSString *path = [self path];
        [arr1 writeToFile:path atomically:YES];
        
    }   
}

+ (NSMutableArray *)readArray
{
    [self fileExist];
    NSString *path = [self path];
    NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
    return  arr;
}

+ (NSString *)path
{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [array lastObject];
    
    path = [NSString stringWithFormat:@"%@/array1.txt", path];
    return path;
}

+ (NSArray *)deleteArray:(NSInteger)index
{
    NSString *path = [self path];
    NSMutableArray *arr = [self readArray];
    [arr removeObjectAtIndex:index];
    NSLog(@"%@", path);
    [arr writeToFile:path atomically:YES];
    
    return arr;
}

@end
